package com.atfusu.controller;

import com.atfusu.bean.entity.HouseImage;
import com.atfusu.result.Result;
import com.atfusu.service.HouseImageService;
import com.atfusu.util.QiniuUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * Title:
 * Author: fusu
 * DateTime:  2022/11/30
 * Description:
 **/
@Controller
@RequestMapping("/houseImage")
public class HouseImageController {

    private static final String PAGE_UPLOAD = "house/upload";

    @DubboReference
    private HouseImageService houseImageService;


    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Map map) {

        map.put("houseId", houseId);
        map.put("type", type);
        return PAGE_UPLOAD;
    }

    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId,
                         @PathVariable Integer type,
                         @RequestParam("file") MultipartFile[] files) throws IOException {

        //接受多个文件
        if (files.length > 0) {
            for (MultipartFile file : files) {
                String fileName = UUID.randomUUID().toString();
                //遍历上传所有接收到的图片
                QiniuUtil.upload2Qiniu(file.getBytes(), fileName);
                //将上传的图片地址添加到数据库内
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setType(type);
                houseImage.setImageUrl("http://rm5dtfln6.hn-bkt.clouddn.com/" + fileName);
                //这里获取到的是文件上传时的名字
                houseImage.setImageName(fileName);
                houseImageService.insert(houseImage);
            }
        }

        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id) {
        //根据id删除图片，根据houseId做页面跳转
        //1.将七牛云服务器的图片删除
        QiniuUtil.deleteFileFromQiniu(houseImageService.getById(id).getImageName());
        //2.将数据库内的地址删除
        houseImageService.delete(id);
        return "redirect:/house/show/" + houseId;
    }
}
